/**
 * 已选择列列表组建
 * guolw@meritit.com
 * @update 2017-03-04
 * */
;(function($){
	$.widget("tempo.grid_columns_selected",{
		options:{
			width:270,
			height:300,
			pendingDiv:{},//待选区
			contextMeta:[],//上下文元信息
			contextHiddenColNames:[],//需要隐藏显示的上下文的字段名称
			udfContextColLabels:{},//用户自定义的上下文字段的显示标签，例如：{name:"评价元素"}，name字段的显示标签修改为"评价元素"
			udfColLabels:[],//自定义列的显示标签列表
			udfColsModel:[],//自定义列的模式
			hasSerialNumber:false,//表格中是否显示“序列”这一列，默认不显示
			udfColumnBinds:[],//自定义列的绑定设置。
			parentDialog:{},//父窗口对象
			rowsData:[],//传递数据
			typeSelectValue:null, //可选参数
			fieldErrorMap:null,   //可选参数
			editable:true,
			showBtn:true,
			leftTreeChangeable:true, //可选参数，左侧列表树是否可修改
			oneRowEdit: $.noop,
			directToEdit:{// 左侧树数据增加到列表时，是否直接进入编辑状态的配置
				inEditDirect:true,// 默认直接进入编辑状态
				selfOnselectRow:function(){},//选中事件
				formEditable:true,//表单是否可编辑
				validIsEdit:function(rowData){
					// 是否需要进入编辑状态，默认可以
					return true;
				}
			},
			ondblClickRow:function(rowid,iRow,iCol,e){},
			onCellSelect:$.noop,
			udfOnSelectRow:function(rowId,status){},
			udfOnSelectAll:function(rowId,status){},
			multiselect:false,
			defaultWidth:["20px","75px","75px","77px"],
			// 删除行后调用的事件
			afterDeleteRow:$.noop,
			// 新增行后调用的事件
			afterAddRow:$.noop,
			// 新增行前调用函数
			beforeAddRow: $.noop,
			multEdit:false,//允许出现多个行编辑
			gridMaxData:-1,
			isRendercboxClass:true,
			//保存节点名称(可选)
			currentModelName:null
		},
		_create:function(){
			var that = this;
			var okClass = 'tempo-mine-grid-columns-status-ok';
			var falseClass = 'tempo-mine-grid-columns-status-false';
			var delBtnInRowClass="tempo-mine-grid-columns-btn-del";
			var udfColsModel= this.options.udfColsModel;
			var hasSerialNumber = this.options.hasSerialNumber;
			var editable = this.options.editable;
			var showBtn = this.options.showBtn;
			var udfColLabels=this.options.udfColLabels;
			var directToEdit = this.options.directToEdit;
			var width=this.options.width;
			var height=this.options.height;
			var leftTreeChangeable=this.options.leftTreeChangeable;
			var udfOnSelectRow=this.options.udfOnSelectRow;
			var udfOnSelectAll=this.options.udfOnSelectAll;
			var multiselect = this.options.multiselect;
			var ondblClickRow = this.options.ondblClickRow;
			var onCellSelect = this.options.onCellSelect;
			var afterDeleteRow=this.options.afterDeleteRow;
			var afterAddRow = this.options.afterAddRow;
			var multEdit = this.options.multEdit;
			//如果列模型定义列表长度和显示标签列表长度不相同，则报错并退出
			if(udfColsModel.length!=udfColLabels.length){
				console.error("The columns model's length is not equals to the columns labels's length! ");
				return;
			}
			for (var i = 0; i < udfColsModel.length; i++) {
				var udfColsModelItem = udfColsModel[i];
				if (udfColsModelItem.editable) {
					udfColsModelItem.editable = editable;
				}
			}
			var gridTable = $('<table/>',{"id":TempoUtils.uuid()}).appendTo(this.element);	
			var gridTableDiv=this.element;
			var pendingDiv = this.options.pendingDiv;
			var contextMeta = this.options.contextMeta;
			
			var udfContextColLabels=this.options.udfContextColLabels;
			
			//放入Map，避免多重循环
			var mapContextHiddenColNames=TempoMineUtils.hashMap();
			var contextHiddenColNames=this.options.contextHiddenColNames;
			for(var i=0;i<contextHiddenColNames.length;i++){
				mapContextHiddenColNames.put(contextHiddenColNames[i],contextHiddenColNames[i]);
			}
			
			var mapUdfColsModel=TempoMineUtils.hashMap();
			//将对象列表和Map关联
			for(var i=0;i<udfColsModel.length;i++){
				mapUdfColsModel.put(udfColsModel[i].name,udfColsModel[i]);
			}
			
			var udfContextColNames=this.options.udfContextColNames;
			var fieldErrorMap=this.options.fieldErrorMap;
			var parentDialog=this.options.parentDialog;
			var rowsData=this.options.rowsData;
			
			var typeSelectValue=this.options.typeSelectValue;
			var udfColumnBinds=this.options.udfColumnBinds;
			var gridMaxData = this.options.gridMaxData;
			//获取节点名称
			var currentModelName = this.options.currentModelName;
			if(!fieldErrorMap){
				if(contextMeta){
					var metaData=contextMeta;
					if(typeof(contextMeta)=="function"){
						var metaData=contextMeta();
					}
					//如果节点是向量自回归使用单独的方式判断
					if(currentModelName&&currentModelName=="vectorautoreg"){
						fieldErrorMap=TempoMineMetaUtils.checkVectorAutoRegression(metaData, rowsData,"map");
					}else {
						fieldErrorMap = TempoMineMetaUtils.checkMetaContainName(metaData, rowsData,"map");
					}
				}else{
					fieldErrorMap = TempoMineMetaUtils.checkMetaContainName([], rowsData,"map");
					console.log("context meta is null or undefined!");
				}
			}
			if(!typeSelectValue){
				typeSelectValue = TempoMineMetaUtils.getFieldTypeSelectValue();
			}
			//将错误列的列表暴露
			this.options.fieldErrorMap=fieldErrorMap;
			
			this.options.gridTable=gridTable;
		    /**
			 * 构建表头名称
			 * 
			 * @param customColNames是一个字符串数组，代表所有要自定义的列表头名称。
			 */
		    var contructColNames=function (udfColLabels){
		    	var prefix="mine.meta_grid_label_";
		    	//首先提取用户自定义的显示标签
		    	var fieldShowLabel=udfContextColLabels.field;
		    	if(!fieldShowLabel){
		    		fieldShowLabel=TempoUtils.locale(prefix+"field");//字段名
		    	}
		    	var nameShowLabel=udfContextColLabels.name;
		    	if(!nameShowLabel){
		    	   nameShowLabel=TempoUtils.locale(prefix+"name");//名称
		    	}
		    	var typeShowLabel=udfContextColLabels.type
		    	if(!typeShowLabel){
			    	typeShowLabel=TempoUtils.locale(prefix+"type");//类型 
		    	}
		
		    	var base= [ "", fieldShowLabel,nameShowLabel,typeShowLabel, "id"];
		    	if (hasSerialNumber) {
		    		var serialNumShowLabel = TempoUtils.locale(prefix+"serial_num");
		    		base= [ "", serialNumShowLabel,fieldShowLabel,nameShowLabel,typeShowLabel, "id"];
		    	}
		    	if(udfColLabels && udfColLabels.length && udfColLabels.length>0){
		    		for(var i=0;i<udfColLabels.length;i++){
		        		base.push(udfColLabels[i]);
		        	}
		    	}else{
		    		console.log("No custom column names in:"+udfColLabels);
		    	}
		    	var deleteBtn=TempoUtils.locale(prefix+"remove");
		    	if (showBtn) {
		    		base.push(deleteBtn);
		    	}
		    	return base;
		    }
		    
		    /**
		     * 设置表格中序列这一列的值，按行1，2，3...顺序显示
		     */
		    var setGridDataSerialNum = function(fieldErrorMap){
		    	var rowIds = gridTable.datagrid("getRowIds");
		    	var allNode = gridTable.find('tr[id] td:nth-child(2)');
		    	for (var i = 0; i < rowIds.length; i++) {
					var rowId = rowIds[i];
					allNode[i].setAttribute('title',i+1)
					allNode[i].innerText=(i+1);
					$("#"+rowId+" .tempo-datagrid-action-wrap").attr("rowId",rowId).unbind('click').bind('click',function(e){
						fromGridToTree($(this).attr("rowId"),fieldErrorMap);
					});
				}
		    }
		    /**
			 * 构建列的显示模式
			 * 
			 * @param customModelObj
			 *            自定义的显示模式
			 */
		    var contructColModel=function(customModelObj,fieldErrorMap){
		    	var base= [{
								name : 'status',
								index : 'status',
								width : that.options.defaultWidth[0],
								sortable:false,
								formatter : function(cellvalue, options, rowObject) {
									if (!cellvalue || cellvalue == ""){
										return "<span class='"+okClass+"'></span>";
									} else {
										return cellvalue;
									}
								}
							},
							{
								name : 'desc',
								index : 'desc',
								width : that.options.defaultWidth[1],
								sortable:false,
								hidden: false
							},
							{
								name : 'name',
								index : 'name',
								sortable:false,
								width : that.options.defaultWidth[2],
								hidden: false
							},
							{
								name : 'type',
								index : 'type',
								sortable:false,
								width : that.options.defaultWidth[3],
								edittype : 'select',
								formatter : 'select',
								editoptions : {
									width : '100%',
									value : typeSelectValue
								},
								align : 'center',
								hidden: false
							},
							{
								name : 'id',
								index : 'id',
								hidden: true
							}
						];
		    	if (hasSerialNumber) {
		    		base.splice(1, 0, {
		    			name : 'serialNumber',
		    			index : 'serialNumber',
		    			width : '50px',
		    			hidden: false,
		    		});
		    	}
		    	// 若mapContextHiddenColNames中只隐藏desc字段，不隐藏name字段，则隐藏name，前端全部显示字段名desc列
		    	if (mapContextHiddenColNames && mapContextHiddenColNames.get("desc") && !mapContextHiddenColNames.get("name")){
		    		mapContextHiddenColNames.remove("desc");
		    		mapContextHiddenColNames.put("name");
		    	}
		    	//设置Hiden属性
		    	for(var i=0;i<base.length;i++){
		    		if(mapContextHiddenColNames.get(base[i].name)){
		    			base[i].hidden=true;
		    		}
		    	}
		    	
		    	var deleteBtnModel={
						name : 'button',
						index : 'button',
						width : '40px',
						align:"center",
				    	buttons:[{
				    		icon:"ui-icon tempo-ui-icon tempo-ui-icon-delete",
				    		click:function(e,dt){
				    			that._saveRow(dt.rowId, gridTable);
				    			fromGridToTree(dt.rowId,fieldErrorMap);
								if (hasSerialNumber) {
									setGridDataSerialNum(fieldErrorMap);
								}
								that.options.afterDeleteRow([dt.rowId]);
				    		},
				    		title:TempoUtils.locale("mine.meta_grid_label_remove")
				    	}]
					}
		    	if(customModelObj && customModelObj.length && customModelObj.length>0){
		    		for(var i=0;i<customModelObj.length;i++){
		        		base.push(that._convertJqColModelToDatagrid(customModelObj[i]));
		        	}
		    	}else{
		    		console.log("No custom column names in:"+customModelObj);
		    	}
		    	if (showBtn) {
		    		base.push(deleteBtnModel);
		    	}
		    	return base;
		    }
		    /**
			 * 初始化字段列表和角色设置表格
			 */
			var initUlAndGridTable = function(fieldErrorMap,rowsData,directToEdit,multEdit) {
				// 状态更改,为所有的数据加上唯一的id值
	 			for (var i = 0; i < rowsData.length; i++) {
					var liDataSetI = rowsData[i];
					if(fieldErrorMap.get(liDataSetI.desc)){
						var errorType = fieldErrorMap.get(liDataSetI.desc).reason;
						var errorTitle = "";
						if (errorType == "nc") {
							errorTitle = "not seted value!";
						} else if (errorType == "type") {
							errorTitle = TempoMineMetaUtils.getTypeChangedTip();
						} else if (errorType == "name") {
							errorTitle = TempoMineMetaUtils.getFieldNotExistsTip();
						}else if(errorType=="idColumn"){
							//该字段已被设置为ID列!
							errorTitle = TempoUtils.locale("mine.meta_field_set_id_column");
						}
						rowsData[i].status = "<span class='"+falseClass+"' title='"+errorTitle+"'></span>";
					}else{
						rowsData[i].status = "<span class='"+okClass+"'></span>";
					}
					// 为所有的数据加上唯一的id值
					if (!rowsData[i].id) {
						rowsData[i].id = TempoUtils.uuid();
					}
				}
				// 初始化右侧表格，表格为单选，变换方式无法操作多个
				if (directToEdit && !directToEdit.inEditDirect){
					// 不是直接进入编辑状态，则默认data为空
					gridTable.datagrid({
						datatype : 'local',
						width : width,
						height : height,
						colNames :contructColNames(udfColLabels),
						colModel : contructColModel(udfColsModel,fieldErrorMap),
						shrinkToFit : true,
						oneRowEdit: that.options.oneRowEdit,
						data:rowsData,
						rowNum:10000,
						multiselect:multiselect,
						ondblClickRow:ondblClickRow,
						onCellSelect:onCellSelect,
						multEdit:multEdit,
						isRendercboxClass:that.options.isRendercboxClass,
						//添加参数event 判断grid中删除事件需要触发其他事件
						onSelectRow:function(rowId,status, event){
							var getSelectRowIds = gridTable.datagrid("getSelectRowIds");
							var gridTableData = gridTable.datagrid("getRowData");
							//选中的行数和表格数据长度相同，则将表格全选按钮选中
							if (getSelectRowIds.length == gridTableData.length) {
								$(gridTable.parent().parent().parent()
									.find(".ui-jqgrid-labels").find("th")[0]).find("input").prop("checked", true);
							}
							//分别为支持单行编辑false和支持多行编辑true的优化
				 			// 若当前是按顺序添加，则不能进入编辑状态
				 			if (!directToEdit.formEditable){
				 				return;
				 			}
							if(multEdit == true){
								gridTable.datagrid("setLastEditId");
							}
							var lastEditId = gridTable.datagrid("getLastEditId");
				 			if (rowId == lastEditId ){
				 				
				 				var rowData = gridTable.datagrid("getRowData", rowId);
					 			if (directToEdit.validIsEdit(rowData)){
					 				gridTable.datagrid("setLastEditId");
					 				gridTable.datagrid("editRow", rowId, true);
					 			}
					 			directToEdit.selfOnselectRow(rowId,status,rowData);
					 			// 自定义行选中事件
					 			udfOnSelectRow(rowId,status, event);
				 				return;
				 			}
				 			if(multEdit == false && !directToEdit.isDataFilterNode){
				 			// 编辑时保存上一次的编辑行
					 			gridTable.datagrid("saveRow", lastEditId);
				 			}
				 			var rowData = gridTable.datagrid("getRowData", rowId);
				 			if (directToEdit.validIsEdit(rowData)){
				 				gridTable.datagrid("editRow", rowId, true);
				 			}
				 			directToEdit.selfOnselectRow(rowId,status,rowData);
				 			// 自定义行选中事件
				 			udfOnSelectRow(rowId,status, event);
				 		},
				 		onSelectAll:function(rowId,status){
				 			// 自定义所有行选中事件
				 			udfOnSelectAll(rowId,status);
				 		}
					});
				} else {
					// 若直接进入编辑状态，则默认data为空
					gridTable.datagrid({
						datatype : 'local',
						width : width,
						height : height,
						colNames :contructColNames(udfColLabels),
						colModel : contructColModel(udfColsModel,fieldErrorMap),
						shrinkToFit : true,
						oneRowEdit: that.options.oneRowEdit,
						data:[],
						multiselect:multiselect,
						rowNum:10000,
						isRendercboxClass:that.options.isRendercboxClass,
						ondblClickRow:ondblClickRow,
						onCellSelect:onCellSelect,
						onSelectRow:function(rowId,status){
							var getSelectRowIds = gridTable.datagrid("getSelectRowIds");
							var gridTableData = gridTable.datagrid("getRowData");
							//选中的行数和表格数据长度相同，则将表格全选按钮选中
							if (getSelectRowIds.length == gridTableData.length) {
								$(gridTable.parent().parent().parent()
									.find(".ui-jqgrid-labels").find("th")[0]).find("input").prop("checked", true);
							}
				 			// 自定义单行选中事件
				 			udfOnSelectRow(rowId,status);
				 		},
				 		onSelectAll:function(rowId,status){
				 			// 自定义所有行选中事件
				 			udfOnSelectAll(rowId,status);
				 		}
					});
					addItemToRightChoosedGrid(gridTable,rowsData);
				}
			}
			/**
			 * 将数据从列表上移至左侧树中 rowId：行编号
			 */
			var fromGridToTree = function(rowId,fieldErrorMap,doNotremoveFromGrid) {
				// 若rowId为空，则将列表中的数据全部移动到左侧树
				var allIds = gridTable.datagrid('getRowIds');
				if (rowId && rowId.trim() != ""){
					allIds = [rowId];
				}
				for (var i=0;i<allIds.length;i++){
					var data = gridTable.datagrid('getRowData', allIds[i]);
					if(fieldErrorMap && fieldErrorMap.get(data.desc) && fieldErrorMap.get(data.desc).meta.type == data.type && fieldErrorMap.get(data.desc).meta.name === data.name){
						console.log("field: {name:\""+data.desc+"\",type:\""+data.type+"\"}!");
					}else{
						if ( leftTreeChangeable ) {
							// 删除多余的属性
							var dataTmp = {};
							dataTmp.status = data.status;
							dataTmp.desc = data.desc;
							dataTmp.name = data.name;
							dataTmp.type = data.type;
							pendingDiv.columnselect('addRowData', dataTmp);
						}
					}
					if(!doNotremoveFromGrid){
						gridTable.datagrid('delRowData', allIds[i]);
					}
				}
			}
			/**
			 * 将数据从列表上移到左侧树中 cwq
			 */
			var JSONFromGridToTree = function(rightDataSelect,rightUnselect,fieldErrorMap) {
				// 先将右侧列表数据添加到左侧
				// if (leftTreeChangeable){
				for (var i=0;i<rightDataSelect.length;i++){
					if (leftTreeChangeable &&
						!(fieldErrorMap && fieldErrorMap.get(rightDataSelect[i].desc)
							&& fieldErrorMap.get(rightDataSelect[i].desc).meta.type == rightDataSelect[i].type
							&& fieldErrorMap.get(rightDataSelect[i].desc).meta.name == rightDataSelect[i].name) ){
						var data = TempoUtils.clone(rightDataSelect[i]);
						//删除多余的属性
						var dataTmp = {}
						dataTmp.status = data.status;
						dataTmp.desc = data.desc;
						dataTmp.name = data.name;
						dataTmp.type = data.type;
						delete data.id;
						that.options.pendingDiv.columnselect('addRowData', dataTmp, false);
					}
					gridTable.datagrid("delRowData", rightDataSelect[i].id);
				}
				// }
				that.options.pendingDiv.columnselect("bindAllDataEvent");

				// 删除右侧表格数据
				// that.options.gridTable[0].addJSONData(rightUnselect);
				//如果全选了，则移除全选框的数据
				that.options.parentDialog.find(".tempo-mine-datafilter-column-right-div")
					.find(".tempo-mine-datafilter-column-dataGrid")
					.find(".ui-jqgrid").find(".ui-jqgrid-view ")
					.find(".ui-jqgrid-hdiv").find(".ui-jqgrid-labels")
					.find("input[type='checkbox']").prop("checked",false);
				that.options.parentDialog.find(".tempo-mine-datafilter-column-right-div").
				find(".tempo-mine-datafilter-column-dataGrid")
					.find(".tempo-searchbar").find(".tempo-searchbar-item").click();
			}
			this.options.getJSONFromGridToTreeFunction=JSONFromGridToTree;
			this.options.fromGridToTreeFunction=fromGridToTree;
			// 右侧列表数据添加
			var addItemToRightChoosedGrid = function(grid,choosedDataSet ) {
				if (choosedDataSet) {
					for (var i = 0; i < choosedDataSet.length; i++) {
						var liDataSetI = choosedDataSet[i];
						var rowId = jsPlumbUtil.uuid();
						var clonedLiDataSetI=TempoUtils.clone(liDataSetI)
						grid.datagrid("addRowData", rowId, clonedLiDataSetI);
						grid.datagrid("editRow", rowId, true);
					}
				}
			}
			
			/**
			 * 根据RowId和cssClass设置显示区的title
			 */
			var setTitleRowIdClass = function(thisObj, rowId, cssClass, title) {
				thisObj.find("#" + rowId + " ." + cssClass).attr("title", title);
			}
			/**
			 * 获取当前编辑和未编辑的列表数据
			 */
			var getAllEditOrData = function(isDataFilterNode){
				var allRowData = gridTable.datagrid('getRowData');
				var allRowIds = gridTable.datagrid('getRowIds');
				//获取下拉框的值
				var selectEdit = gridTable.find("tr[id] td select");			
				var mapEdit_V = {};
				if(selectEdit.length > 0){
					$.each(selectEdit,function(i,v){
						var val = $(v).val();
						var descr = $(v).closest("td").attr("aria-describedby").split("_");
						var fieldName = descr[descr.length-1];
						var id = $(v).closest("tr").attr("id");
						var nameVal = {"fieldName":fieldName,"value":val};
						if(mapEdit_V[id] == null){
							mapEdit_V[id] = [];
						}
						mapEdit_V[id].push(nameVal);
					});
				}
				//获取编辑框的值//表格第一列的复选框不碍事
				var inputEdit = gridTable.find("tr[id] td input");
				if(inputEdit.length > 0){
					$.each(inputEdit,function(i,v){
						var val = $(v).val();
						var descr = $(v).closest("td").attr("aria-describedby").split("_");
						var fieldName = descr[descr.length-1];
						var id = $(v).closest("tr").attr("id");
						var nameVal = {"fieldName":fieldName,"value":val};
						if(mapEdit_V[id] == null){
							mapEdit_V[id] = [];
						}
						mapEdit_V[id].push(nameVal);
					});
				}
				//将编辑框中的值放入获取的表格数据中
				var arrayMapEdit = Object.keys(mapEdit_V);
				if(arrayMapEdit.length > 0){
					for(var i = 0 ; i < arrayMapEdit.length ; i++){
						var modifyid = arrayMapEdit[i];//编辑的行的id
						var modfiyIndex = allRowIds.indexOf(modifyid);//编辑中的行在表格中的位置
						var modifyRow = allRowData[modfiyIndex];//要修改的行
						var fieldNameValue = mapEdit_V[modifyid];//要修改的行的名称和值的映射关系的数组·=·
						//数据过滤节点需要做特殊处理
						if(isDataFilterNode && fieldNameValue.length == 5){
							if(fieldNameValue[2].value == null){
								fieldNameValue[2].value = fieldNameValue[4].value;
							}
						}else if(isDataFilterNode && fieldNameValue.length == 7){
							if(fieldNameValue[2].value == null){
								fieldNameValue[2].value = fieldNameValue[5].value;
								fieldNameValue[6].value = fieldNameValue[5].value;
							}
						}
						$.each(fieldNameValue,function(i,v){
							if(modifyRow[v["fieldName"]] != null){
								modifyRow[v["fieldName"]]=v["value"];
							}
						});
					}
				}
				//近N时时间对值进行赋值
				for(var j = 0; j<allRowData.length ; j++){
					//过滤的方式
					var rowIds = gridTable.datagrid("getRowIds");
					if (rowIds[j]) {
						var filterWay=gridTable.find("tr[id="+(rowIds[j])+"]").find("select[id="+(rowIds[j])+"_filterconditions]").selectmenu("getValue");
						if(filterWay == "neardatetime"){
							var inputValue=gridTable.find("tr[id="+(rowIds[j])+"]").find("#udfInput").val();
							var selectValue=gridTable.find("tr[id="+(rowIds[j])+"]").find("#udfSelect").selectmenu("getValue");
							var value=inputValue+selectValue;
							allRowData[j].value=value
						}
					}
				}
				return allRowData;
			}
			this.options.getAllEditOrData = getAllEditOrData;
			/**
			 * 绑定事件
			 */
			var bindEvent = function(fieldErrorMap,gridTable) {
				// 全选反选事件绑定
				parentDialog.find('button[name=columnselect]').unbind('click').bind("click",
						function(e) {
							var e = e || window.event;
							var id = $(this).attr('id');
							// 缓存表格id
							that.options.tableId = gridTable.attr("id");
							if (id == 'reverseselect') {
								// 如果是点击全选左移按钮,将右边表格中所有行移到左边列表中
								if (!that.options.directToEdit || that.options.directToEdit.inEditDirect){
									gridTable.find(".jqgrow:visible").each(function(){
										var rowId =  $(this).attr("id");
										fromGridToTree(rowId,fieldErrorMap);
									});
								} else {
									var lastEditId = gridTable.datagrid("getLastEditId");
									if (lastEditId && lastEditId != "" && !that.options.directToEdit.isDataFilterNode){
										gridTable.datagrid("saveRow", lastEditId);
									}
									var rightData = gridTable.datagrid('getRowData');
									if(that.options.directToEdit.isDataFilterNode){
										for(var i = 0 ; i < rightData.length ; i++){
											if(rightData[i].value.indexOf('<span') > -1){
												rightData[i].filterconditions = gridTable.find("tr:eq("+(i+1)+") select[name=filterconditions]").selectmenu("getValue");
												rightData[i].valueway = gridTable.find("tr:eq("+(i+1)+") select[name=valueway]").selectmenu("getValue");
												rightData[i].value = gridTable.find("tr:eq("+(i+1)+") select[name=value]").selectmenu("getValue");
											}
										}
									}
									var selectAll = (rightData.length==gridTable.find(".jqgrow:visible").length)?true:false;
									
									if(selectAll && !leftTreeChangeable){
										that.options.pendingDiv.columnselect("bindAllDataEvent");
//										// 清空右侧表格数据
										that.options.gridTable.datagrid("clearGridData");
									}else{
										// 先将右侧列表数据添加到左侧
										gridTable.find(".jqgrow:visible").each(function(){
											var rowId =  $(this).attr("id");
											var rightdata =  gridTable.datagrid('getRowData',rowId);
											if (leftTreeChangeable){
												if (!fieldErrorMap || !fieldErrorMap.get(rightdata.desc) || fieldErrorMap.get(rightdata.desc).meta.type != rightdata.type){
													that.options.pendingDiv.columnselect('addRowData', rightdata, false);
												}
											}
											if(!selectAll){
												gridTable.datagrid('delRowData', rowId);
											}
										});
										if(selectAll){
											that.options.pendingDiv.columnselect("bindAllDataEvent");
//											// 清空右侧表格数据
											that.options.gridTable.datagrid("clearGridData");
										}
									}
									//左移右移清除表头中全选事件
									var gridDiv = that.options.gridTable.parent().parent().parent();
                                    gridDiv.find(".tempo-datagrid-cbox-container").find(".tempo-checkbox-nolabel").attr("checked",false);
                                    gridDiv.find(".tempo-datagrid-cbox-container").find(".tempo-checkbox-nolabel").prop("checked", false);

								}
								that.options.afterDeleteRow([]);
							} else {
								//如果是点击全选右移按钮,将左边的数据以及右边已选数据拼接好，并重新初始化表格	
								var ul = parentDialog.find('.tempo-mine-column-list');
								var dataSelectId = parentDialog.find('input[name=dataselect]:checked').attr('id');								
								if (!that.options.directToEdit || that.options.directToEdit.inEditDirect || that.options.multEdit){
									if(!that.options.directToEdit || that.options.directToEdit.inEditDirect){
										var rowDataNums = gridTable.datagrid('getRowData').length;
										if(gridMaxData != -1 && rowDataNums >= gridMaxData){
											$("<div/>").alert({
												msg : TempoUtils.locale("mine.zuiduoxuanze")+gridMaxData+TempoUtils.locale("mine.geziduan"),
												title : TempoUtils.locale("mine.prompt")
											});
											return;
										}
										var count = rowDataNums;		
										ul.find("li:visible").each(function(){
								          	var data = TempoUtils.clone($(this).data("data"));
								          	var type = data.type;
								      		if (dataSelectId == 'number' && TempoMineMetaUtils.isNumber(type.toUpperCase()) ||
							        				type.toUpperCase() == dataSelectId.toUpperCase() || 
							        				dataSelectId == 'all') {
								      			if(gridMaxData != -1 && count >= gridMaxData){
													$("<div/>").alert({
														msg : TempoUtils.locale("mine.zuiduoxuanze")+gridMaxData+TempoUtils.locale("mine.geziduan"),
														title : TempoUtils.locale("mine.prompt")
													});
													return false
												}
									        	fromTreeToGrid($(this),data,fieldErrorMap);
									        	count++;
								      		}
								        });
									}else{
										var JSONArray = [];
										ul.find("li:visible").each(function(){
											//优化右移时的效率 每个is大概需要0.014S时间 不用判断是否隐藏，下边if里已经判断
//											var isHide = $(this).is(':hidden');
								          	var data = TempoUtils.clone($(this).data("data"));
								          	var datatypes = parentDialog.find(".tempo-columnselect-datatype").find('input');
								          	var showRadios = [];
								          	var isContainAll = false;
								          	for (var i = 0; i < datatypes.length; i++) {
								          		var dataType = $(datatypes[i]).attr("id");
								          		if ("all" == dataType) {
								          			isContainAll = true;
								          		} else {
								          			showRadios.push(dataType.toUpperCase());
								          		}
								          	}
								          	var type = data.type;
								          	if (dataSelectId == 'all') {
								          		if (showRadios.indexOf('NUMBER') > -1 && TempoMineMetaUtils.isNumber(type.toUpperCase()) ||
								          				showRadios.indexOf(type.toUpperCase()) > -1) {
								          			var jsonNode = JSONfromTreeToGrid($(this),data,fieldErrorMap);
									      			if(Object.keys(jsonNode).length > 0){
									      				JSONArray.push(jsonNode);
									      			}
								          		}
								          	} else if (dataSelectId == 'number' && TempoMineMetaUtils.isNumber(type.toUpperCase()) ||
							        				type.toUpperCase() == dataSelectId.toUpperCase()) {
								      			var jsonNode = JSONfromTreeToGrid($(this),data,fieldErrorMap);
								      			if(Object.keys(jsonNode).length > 0){
								      				JSONArray.push(jsonNode);
								      			}
								      		}
								        });
										
										var rightData = getAllEditOrData();
										//过滤值可填写<NULL>和<BLANK>，点击确定后再次打开节点，值显示为空，点击输入框后显示<NULL></NULL>和<BLANK></BLANK>进行转移
										for(var i = 0 ; i < rightData.length ; i++){
											var value=TempoMineUtils.encodeHTML(rightData[i].value);
											rightData[i].value=value;
										}
										var allData = rightData.concat(JSONArray);
										that.options.gridTable[0].addJSONData(allData);
									}
								} else {
									var lastEditId = gridTable.datagrid("getLastEditId");
									if (lastEditId && lastEditId != "" && !that.options.directToEdit.isDataFilterNode){
										gridTable.datagrid("saveRow", lastEditId);
									}
									var rightData = gridTable.datagrid('getRowData');
									//过滤值可填写<NULL>和<BLANK>，点击确定后再次打开节点，值显示为空，点击输入框后显示<NULL></NULL>和<BLANK></BLANK>进行转移
									for(var i = 0 ; i < rightData.length ; i++){
										var value=TempoMineUtils.encodeHTML(rightData[i].value);
										rightData[i].value=value;
									}
									if(that.options.directToEdit.isDataFilterNode){
										for(var i = 0 ; i < rightData.length ; i++){
											if(rightData[i].valueway.indexOf('<span') > -1){
												rightData[i].filterconditions = gridTable.find("tr:eq("+(i+1)+") select[name=filterconditions]").selectmenu("getValue");
												rightData[i].valueway = gridTable.find("tr:eq("+(i+1)+") select[name=valueway]").selectmenu("getValue");
												rightData[i].value = gridTable.find("tr:eq("+(i+1)+") select[name=value]").selectmenu("getValue");
											}
										}
									}
									// 左侧所有数据
									var leftData = [];
									ul.find("li:visible").each(function(){
							          	var data = TempoUtils.clone($(this).data("data"));
							          	var type = data.type;
							      		if (dataSelectId == 'number' && TempoMineMetaUtils.isNumber(type.toUpperCase()) ||
						        				type.toUpperCase() == dataSelectId.toUpperCase() || 
						        				dataSelectId == 'all'||(dataSelectId.toUpperCase()=="TIMESTAMP"&&type.toUpperCase()=="DATETIME")) {
											// 设置udfColModel中的默认值
											if (that.options.udfColsModel && that.options.udfColsModel.length > 0) {
												for (var i = 0; i < that.options.udfColsModel.length; i++) {
													var colModelItem = that.options.udfColsModel[i];
													if (colModelItem.defaultValue) {
														data[colModelItem.name] = typeof colModelItem.defaultValue == 'function' ?
															colModelItem.defaultValue.call(window, data) : colModelItem.defaultValue;
													}
												}
											}
											if (!data.id) {
												data.id = TempoUtils.uuid();
											}
											leftData.push(data);
											if (that.options.leftTreeChangeable) {
												$(this).remove();
											}
										}
							        });
									that.options.beforeAddRow(leftData);
									// 右侧所有数据
									var allData = rightData.concat(leftData);
									that.options.gridTable[0].addJSONData(allData);
								}
								that.options.afterAddRow();
							}
							
							if (hasSerialNumber) {
								setGridDataSerialNum(that.options.fieldErrorMap);
							}
                            //左移右移清除表头中全选事件
                            var gridDiv = that.options.gridTable.parent().parent().parent();
                            gridDiv.find(".tempo-datagrid-cbox-container").find(".tempo-checkbox-nolabel").attr("checked",false);
                            gridDiv.find(".tempo-datagrid-cbox-container").find(".tempo-checkbox-nolabel").prop("checked", false);
							e.preventDefault();
						});
				// 向右选择按钮事件绑定
				parentDialog.find("#tempo-columnselect-right-remove-btn").unbind('click').bind(
						"click",
						function(e) {
							var ul = parentDialog.find('.tempo-mine-column-list');
							if (!that.options.directToEdit || that.options.directToEdit.inEditDirect){
								var rowDataNums = gridTable.datagrid('getRowData').length;
								if(gridMaxData != -1 && rowDataNums >= gridMaxData){
									$("<div/>").alert({
										msg : TempoUtils.locale("mine.zuiduoxuanze")+gridMaxData+TempoUtils.locale("mine.geziduan"),
										title : TempoUtils.locale("mine.prompt")
									});
									return;
								}
								var count = rowDataNums;
								ul.find("li:visible").each(
										function() {
											if ($(this).hasClass('tempo-mine-column-backgroundcolor') && $(this).attr("class").indexOf("nodisplay") == -1) {
												if(gridMaxData != -1 && count >= gridMaxData){
													$("<div/>").alert({
														msg : TempoUtils.locale("mine.zuiduoxuanze")+gridMaxData+TempoUtils.locale("mine.geziduan"),
														title : TempoUtils.locale("mine.prompt")
													});
													return false
												}
												var data = TempoUtils.clone($(this).data("data"));
												fromTreeToGrid($(this), data,fieldErrorMap);
												count++;
											}
										});
								
							}else{//右移默认不打开编辑的执行如下
								var JSONArray = [];
								ul.find("li").each(
										function() {
											if ($(this).hasClass(
													'tempo-mine-column-backgroundcolor') && $(this).attr("class").indexOf("nodisplay") == -1) {
												var data = TempoUtils.clone($(this).data("data"));
												var jsonNode = JSONfromTreeToGrid($(this),data,fieldErrorMap);
								      			if(Object.keys(jsonNode).length > 0){
								      				if (!jsonNode.id) {
								      					jsonNode.id = TempoUtils.uuid();
													}
								      				JSONArray.push(jsonNode);
								      			}
											}
										});
								
								var rightData = getAllEditOrData(that.options.directToEdit.isDataFilterNode);
								//过滤值可填写<NULL>和<BLANK>，点击确定后再次打开节点，值显示为空，点击输入框后显示<NULL></NULL>和<BLANK></BLANK>
								for(var i = 0 ; i < rightData.length ; i++){
									var value=TempoMineUtils.encodeHTML(rightData[i].value);
									rightData[i].value=value;
								}
								that.options.beforeAddRow(JSONArray);
								var allData = rightData.concat(JSONArray);	
								that.options.gridTable[0].addJSONData(allData);
								//移除全选框
								$($(that.options.gridTable[0]).parent().parent().parent().find(".ui-jqgrid-labels").find("th")[0]).find("input").attr("checked",false)
							}	
							if (hasSerialNumber) {
								setGridDataSerialNum(that.options.fieldErrorMap);
							}
							that.options.afterAddRow();
							e.preventDefault();
						});
				// 向左选择按钮事件绑定
				parentDialog.find("#tempo-columnselect-left-remove-btn").unbind('click').bind(
						"click",
						function(e) {//cwq
							if (!that.options.directToEdit || that.options.directToEdit.inEditDirect){//默认打开编辑 用以前的方法
								var ids = gridTable.datagrid('getRowIds');
								for (var i = 0; i < ids.length; i++) {
									var id = ids[i];
									if (parentDialog.find('#' + id).hasClass(
											'ui-state-highlight')) {
										that._saveRow(id, gridTable);
										fromGridToTree(id,fieldErrorMap);
									}
								}
							}else{//默认不打开编辑，采用优化的新方法
								var alRData = getAllEditOrData(that.options.directToEdit.isDataFilterNode);
								//过滤值可填写<NULL>和<BLANK>，点击确定后再次打开节点，值显示为空，点击输入框后显示<NULL></NULL>和<BLANK></BLANK>
								for(var i = 0 ; i < alRData.length ; i++){
									var value=TempoMineUtils.encodeHTML(alRData[i].value);
									alRData[i].value=value;
								}
								var rSData = [];//右侧已经选中的data
								var rUSData = [];//右侧未选中的data
								// 右侧有复选框的情况下，全部选中的字段
								var rsList = that.options.gridTable.find("tr[id] td[aria-describedby*='_cb'] input:checked").closest("tr");//右侧的选中列表
								// 找出搜索之后并选中的字段
								var rsListLen = rsList.length;
								for (var i = rsListLen - 1; i >= 0; i--){
									if ( rsList.eq(i).is(":hidden") ) {
										rsList.splice(i, 1);
									}
								}
								// 如果右侧没有复选框，使用下面这个
								if (rsList && rsList.length == 0) {
									// 侧没有复选框的情况下选中的字段
									rsList = that.options.gridTable.find("tr[aria-selected=true]");
								}
								var rOriList = that.options.gridTable.find("tr[id]");
								$.each(rsList,function(i,v){
									var botIndex = rOriList.index(v);//获得选中的列表的下标
									rSData.push(alRData[botIndex]);
									delete alRData[botIndex];
								});
								for(var j = 0 ,len = alRData.length ; j < len ; j++){
									var temp = alRData[j];
									if(temp != null){
										rUSData.push(temp);
									}
								}
								JSONFromGridToTree(rSData,rUSData,fieldErrorMap);
							}
                            //左移右移清除表头中全选事件
                            var gridDiv = that.options.gridTable.parent().parent().parent();
                            gridDiv.find(".tempo-datagrid-cbox-container").find(".tempo-checkbox-nolabel").attr("checked",false);
                            gridDiv.find(".tempo-datagrid-cbox-container").find(".tempo-checkbox-nolabel").prop("checked", false);
							if (hasSerialNumber) {
								setGridDataSerialNum(that.options.fieldErrorMap);
							}
							that.options.afterDeleteRow([]);
							e.preventDefault();
						});
			}
			/**
			 * 将数据从左侧树上移至列表中 comp：当前元素 data：数据 btn_tag:grid_columns_selected_with_btn组件标志默认是否打开编辑 默认true打开 btn_remove:去重标志位 默认false
			 * 去重标志位只限于左边列表一直存在数据，右边表格需要去重时使用
			 */
			var fromTreeToGrid = function(comp, data, fieldErrorMap,btn_tag,btn_remove) {
				
				var rowId = jsPlumbUtil.uuid();
				var isAllHaveDefault=setUdfColumnsDefaultValue(data);
				var len = 0;
				if(btn_remove && btn_remove == true){
					len = gridTable.find('tr[id] td[aria-describedby$="_name"][title="'+data.name+'"]').length;
				}
				if(len <= 0){
					if (!data.id) {
						data.id = rowId;
					}
					gridTable.datagrid("addRowData", rowId, data);
					if (!directToEdit || directToEdit.inEditDirect){
						if(btn_tag == null || btn_tag != false ){
							gridTable.datagrid("editRow", rowId, true);
						}
					}
					if ( leftTreeChangeable ) {
						comp.remove();
					}
				}
			
			}
			
			/**
			 * 把往表格添加的数据组装成json
			 */
			var JSONfromTreeToGrid = function(comp, data, fieldErrorMap,btn_tag,btn_remove) {
				
				var rowId = TempoUtils.uuid();
				if(!data.id || '' == data.id.trim()){
					data["id"] = rowId;
				}
				var isAllHaveDefault=setUdfColumnsDefaultValue(data);
				var len = 0;
				if(btn_remove && btn_remove == true){
					len = gridTable.find('tr[id] td[aria-describedby$="_name"][title="'+data.name+'"]').length;
				}
				if ( leftTreeChangeable ) {
					comp.remove();
				}
				//去重和返回数据
				if(len <= 0){
					return data;
				}else{
					return {};
				}
			}
			this.options.fromTreeToGridFunction=fromTreeToGrid;
			this.options.getJSONfromTreeToGridFunction=JSONfromTreeToGrid;
			
			/**
			 * 设置用户自定义列的默认值<br>
			 * data 从左侧树选择到的数据<br>
			 * 如果所有列都有默认值则返回true<br>
			 * */
			var setUdfColumnsDefaultValue =function(data){
				var isAllHaveDefault=true;
				for(var i=0;i<udfColsModel.length;i++){
					var colModel=udfColsModel[i];
					if(colModel.defaultValue!=null && typeof(colModel.defaultValue)!="undefined" ){
						//对默认值进行不同的处理
					    data[colModel.name] = typeof colModel.defaultValue == 'function' ? 
					    		colModel.defaultValue.call(window, data) : colModel.defaultValue;
					}else{
						isAllHaveDefault=false;
					}
				}
				return isAllHaveDefault
			}
			/**
			 * 获取编辑状态下的列表的值 grid：列表所在区域
			 */
			var getEditRowData = function(thisGrid) {
				var gridDatas=TempoMineUtils.getMetaJqgrdData(thisGrid,udfColsModel)
				$.each(gridDatas.rowDatas,function(i,dataItem) {
					dataItem.button="";
					dataItem.status="";
				});
				return gridDatas;
			}
			//设置一个全局的提取数据的返回函数
			this.options.getEditRowDataFunction=getEditRowData;
			/**
			 * 给列表添加数据，并进入编辑状态 grid:列表 datas
			 */
			var addEditRowData = function(gridTable, datas) {
				if (!datas || datas.length == 0) {
					return;
				}
				for (var i = 0; i < datas.length; i++) {
					var rowId = jsPlumbUtil.uuid();
					gridTable.datagrid("addRowData", rowId, datas[i]);
					gridTable.datagrid("editRow", rowId, true);
				}
			}
			initUlAndGridTable(fieldErrorMap,rowsData,directToEdit,multEdit);
			bindEvent(fieldErrorMap,gridTable);
		},
		_setOption:function(key,val){
			
		},
		_bindEvent:function(ul) {
			
		},
		_convertJqColModelToDatagrid:function(item){
			// 将jqgrid类型的colmodel转换为datagrid需要的colmodel
			// 输入框完善
			if (!item.edittype || item.edittype == "text"){
				item.edittype = "validatebox";
				if (!item.editoptions){
					item.editoptions = {};
				}
				// 宽度赋值
				if (item.width && !item.editoptions.width){
					item.editoptions.width = item.width;
				}
			} else if (item.edittype == "select"){
				item = TempoMineUtils.getDatagridSelectColModel(item);
			}
			return item;
		},
		getGridTable:function(){
			return this.options.gridTable;
		},
		getFieldErrorMap:function(){
			return this.options.fieldErrorMap;
		},
		clearTable: function() {
			this.getFromGridToTreeFunction()("",this.getFieldErrorMap());
		},
		/**
		 * 提取statusFormatter函数对象
		 * */
		getStatusFormatterFunction:function (){
			return this.options.statusFormatterFunction;
		},
		getEditRowData:function(){
			return this.options.getEditRowDataFunction(this.options.gridTable);
		},
		getRowData:function(){
			var grid = this.options.gridTable;
			var allRowData = grid.datagrid("getRowData");
			for (var i=0;i<allRowData.length;i++){
				var item = allRowData[i];
				item.button = "";
				item.status = "";
			}
			return allRowData;
		},
		/**
		 * 返回从左侧树到右侧列表的选择函数
		 * */
		getFromTreeToGridFunction:function(){
			return this.options.fromTreeToGridFunction;
		},
		/**
		 * 返回从右侧列表到左侧树的选择函数
		 * */
		getFromGridToTreeFunction:function(){
			return this.options.fromGridToTreeFunction;
		},
		/**
		 * 返回从左侧树到右侧列表的批量操作的数据集合函数
		 */
		getJSONfromTreeToGridFunction:function(){
			return this.options.getJSONfromTreeToGridFunction;
		},
		/**
		 * 返回从右侧列表到左侧树的
		 */
		JSONFromGridToTreeFunction:function(){
			return this.options.getJSONFromGridToTreeFunction;
		},
		/**
		 * 获得右侧列表编辑中和未编辑中的所有数据
		 */
		getAllEditOrDataFunction:function(){
			return this.options.getAllEditOrData;
		},
		_saveRow:function(rowId, gridTable){
			// 判断列表是否直接进入编辑状态，若是，则直接返回
			if (!this.options.directToEdit || this.options.directToEdit.inEditDirect){
				return;
			}
			var lastEditId = gridTable.datagrid("getLastEditId");
			if (!lastEditId || lastEditId.trim() == ""){
				return;
			}
			if(!this.options.directToEdit.isDataFilterNode){
				if (rowId && rowId == lastEditId){
					gridTable.datagrid("saveRow", lastEditId);
				} else {
					gridTable.datagrid("saveRow", lastEditId);
				}
			}
		},
		//触发右侧表格的数据转移到左侧树上（表转置节点优化时增加，其它节点应该也可以用）
		reverseSelectRightToLeft:function(){
			var that = this;
			var gridTable = that.options.gridTable;
			// 先将右侧列表数据添加到左侧
			gridTable.find(".jqgrow:visible").each(function(){
				var rowId =  $(this).attr("id");
				var rightdata =  gridTable.datagrid('getRowData',rowId);
				//表格字段不存在则不需要添加
				if(rightdata.status && rightdata.status.indexOf("-ok") > -1){
					that.options.pendingDiv.columnselect('addRowData', rightdata, false);
				}
			});
			that.options.pendingDiv.columnselect("bindAllDataEvent");
			// 清空右侧表格数据
			that.options.gridTable.datagrid("clearGridData");
		}
	});
})(jQuery)